package pl.edu.agh.gameserv.gameprovider.tictactoe;

import java.io.Serializable;
import java.util.regex.Pattern;

import javax.ejb.Stateless;

import pl.edu.agh.gameserv.gameproviderapi.GameLogic;
import pl.edu.agh.gameserv.gameproviderapi.IllegalMoveException;

@Stateless
public class GameLogicImpl implements GameLogic, Serializable {

	int[][] state = new int[][] { { -1, -1, -1}, { -1, -1, -1 }, { -1, -1, -1 } };
	boolean isFinished = false;
	String score;
	static Pattern pattern = Pattern.compile("^(\\d+),(\\d+)$");

	@Override
	public String getScore() {
		// TODO Auto-generated method stub
		return score;
	}

	@Override
	public void makeMove(int user, String move) throws IllegalMoveException {
		if (isFinished)
			throw new IllegalMoveException();

		// Matcher match = pattern.matcher(move);
		// if (!match.find())
		// throw new IllegalMoveException();
		// int x = Integer.parseInt(match.group(1));
		// int y = Integer.parseInt(match.group(2));
		int x = Integer.parseInt(move.substring(0, 1));
		int y = Integer.parseInt(move.substring(1));

		if (x >= 3 || y >= 3)
			throw new IllegalMoveException();
		if (state[x][y] != -1)
			throw new IllegalMoveException();

		state[x][y] = user;

		if (state[x][0] == user && state[x][1] == user && state[x][2] == user || state[0][y] == user && state[1][y] == user && state[2][y] == user
				|| state[0][0] == user && state[1][1] == user && state[2][2] == user || state[0][2] == user && state[1][1] == user
				&& state[2][0] == user) {
			score = "User " + user + " won.";
			isFinished = true;
		} else {
			boolean isFull = true;
			for (int i = 0; i < 3; i++)
				for (int j = 0; j < 3; j++)
					isFull &= state[i][j] != -1;
			if (isFull) {
				isFinished = true;
				score = "Tie";
			}
		}

	}

	@Override
	public Boolean isFinished() {
		return isFinished;
	}

	@Override
	public String[][] getSituation() {
		String[][] desc = new String[3][3];

		for (int i = 0; i < 3; i++)
			for (int j = 0; j < 3; j++) {
				if (state[i][j] == -1)
					desc[i][j] = " ";
				else
					desc[i][j] = "" + state[i][j];

			}
		return desc;

		// return status;
		// fn(0,0) + "|" + fn(0,1) + "|" + fn(0,2) + "\r\n"
		// + "----\n"
		// + fn(1,0) + "|" + fn(1,1) + "|" + fn(1,2) + "\r\n"
		// + "----\n"
		// + fn(2,0) + "|" + fn(2,1) + "|" + fn(2,2) + "\r\n"
		// ;
	}

	String fn(int x, int y) {
		int num = state[x][y];
		if (num == -1)
			return " ";
		else
			return "" + num;

	}

}
